package user

import (
	"context"

	"mall/common/globalkey"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.BaseMsgResp, err error) {
	if req.CaptchaId != nil && req.Captcha != nil {
		if ok := l.svcCtx.Captcha.Verify("CAPTCHA_"+*req.CaptchaId, *req.Captcha, true); !ok {
			return nil, errorx.NewCodeError(errorcode.InvalidArgument,
				l.svcCtx.Trans.Trans(l.ctx, "login.wrongCaptcha"))
		}
	}

	_, err = l.svcCtx.BackendRpc.CreateUser(l.ctx, &backendclient.UserInfo{
		Username:     &req.Username,
		Password:     &req.Password,
		Nickname:     &req.Username,
		HomePath:     pointy.GetPointer("/dashboard"),
		Email:        req.Email,
		Status:       pointy.GetPointer(uint32(globalkey.StatusEnabled)),
		DepartmentId: pointy.GetPointer(l.svcCtx.Config.ProjectConf.DefaultDepartmentId),
		PositionIds:  []uint64{l.svcCtx.Config.ProjectConf.DefaultPositionId},
		RoleIds:      []uint64{l.svcCtx.Config.ProjectConf.DefaultRoleId},
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, "login.signupSuccessTitle"),
	}, nil
}
